import 'dart:io';
import 'dart:ui';

import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_2b_client/pages/AddGoodsPage.dart';
import 'package:flutter_2b_client/pages/CheckInventoryRecordDetailPage.dart';
import 'package:flutter_2b_client/pages/EditGoodsPage.dart';
import 'package:flutter_2b_client/pages/GoodsPage.dart';
import 'package:flutter_2b_client/pages/MarketCheckInventoryRecordPage.dart';
import 'package:flutter_2b_client/pages/MarketDeliveryDetailOrderPage.dart';
import 'package:flutter_2b_client/pages/MarketGoodsPage.dart';
import 'package:flutter_2b_client/pages/ScanBarcodePage.dart';
import 'package:flutter_2b_client/pages/UpdatePassworPage.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/TypeConvertUtils.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'apis/EmployeeApi.dart';
import 'apis/NotificationApi.dart';
import 'pages/CheckInventoryRecordPage.dart';
import 'pages/GoodsDetailPage.dart';
import 'pages/GoodsScratchDetailPage.dart';
import 'pages/GoodsScratchPage.dart';
import 'pages/HomeScaffold.dart';
import 'pages/LogInPage.dart';
import 'pages/MarketCheckInventoryRecordDetailPage.dart';
import 'pages/MarketDetailOrderPage.dart';
import 'pages/MarketDetailPage.dart';
import 'pages/MarketPage.dart';
import 'service/MyBackgroundService.dart';
import 'store/EmployeeAuthorizationStore.dart';
import 'theme/color_schemes.dart';
import 'theme/custom_color.dart';

final GoRouterRedirect _checkAuthorizationRedirect = (context, state) async {
  var sharedPreferences = await SharedPreferences.getInstance();
  var authorization =
      sharedPreferences.getString(HttpHeaders.authorizationHeader);
  if (authorization == null) {
    return LogInPage.path;
  } else {
    return null;
  }
};

final materialRouterGlobalKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> _shellNavigatorKey =
    GlobalKey<NavigatorState>(debugLabel: 'shell');
final GlobalKey<NavigatorState> rootGoRouterKey =
    GlobalKey<NavigatorState>(debugLabel: 'root');

final _router = GoRouter(
  debugLogDiagnostics: true,
  initialLocation: "/",
  navigatorKey: rootGoRouterKey,
  routes: [
    ShellRoute(
      parentNavigatorKey: rootGoRouterKey,
      navigatorKey: _shellNavigatorKey,
      builder: (context, state, Widget child) => HomeScaffold(
        child: child,
      ),
      routes: bottomTabBarItems
          .map((e) => GoRoute(
                parentNavigatorKey: _shellNavigatorKey,
                path: e.path,
                builder: (context, state) {
                  return e.page;
                },
                redirect: _checkAuthorizationRedirect,
              ))
          .toList(),
    ),
    GoRoute(
      parentNavigatorKey: rootGoRouterKey,
      path: MarketPage.path,
      builder: (context, state) => const MarketPage(),
      redirect: _checkAuthorizationRedirect,
      routes: [
        GoRoute(
          path: ":marketId",
          parentNavigatorKey: rootGoRouterKey,
          builder: (context, state) {
            return MarketDetailPage(
                int.parse(state.pathParameters["marketId"]!));
          },
          redirect: _checkAuthorizationRedirect,
          routes: [
            GoRoute(
              parentNavigatorKey: rootGoRouterKey,
              path: "orders/:orderId",
              builder: (context, state) {
                return MarketOrderDetailPage(
                    int.parse(state.pathParameters["orderId"]!));
              },
              redirect: _checkAuthorizationRedirect,
            ),
            GoRoute(
              parentNavigatorKey: rootGoRouterKey,
              path: "deliveryOrders/:orderId",
              builder: (context, state) {
                return MarketDeliveryOrderDetailPage(
                    int.parse(state.pathParameters["orderId"]!));
              },
            ),
            GoRoute(
              path: "goods",
              parentNavigatorKey: rootGoRouterKey,
              builder: (context, state) {
                return MarketGoodsPage(
                  marketId: int.parse(state.pathParameters["marketId"]!),
                  marketName: state.uri.queryParameters["marketName"]!,
                );
              },
            ),
          ],
        ),
      ],
    ),
    GoRoute(
      parentNavigatorKey: rootGoRouterKey,
      path: LogInPage.path,
      builder: (context, state) => LogInPage(),
    ),
    GoRoute(
      path: ScanBarcodePage.path,
      parentNavigatorKey: rootGoRouterKey,
      builder: (context, state) {
        var marketDeliveryOrderId =
            state.uri.queryParameters["marketDeliveryOrderId"];
        var marketOrderId = state.uri.queryParameters["marketOrderId"];
        return ScanBarcodePage(
          marketDeliveryOrderId: marketDeliveryOrderId?.toIntOrNull(),
          marketOrderId: marketOrderId?.toIntOrNull(),
          checkInventoryRecordId:
              state.uri.queryParameters["marketOrderId"]?.toIntOrNull(),
          marketCheckInventoryRecordId: state
              .uri.queryParameters["marketCheckInventoryRecordId"]
              ?.toIntOrNull(),
        );
      },
    ),
    GoRoute(
        path: "/goods",
        redirect: _checkAuthorizationRedirect,
        builder: (context, state) {
          var returnItem = state.uri.queryParameters["returnItem"];
          var multiSelect = state.uri.queryParameters["multiSelect"];
          var excludeIds = state.uri.queryParameters["excludeIds"];
          return GoodsPage(
            editMarketOrderId:
                state.uri.queryParameters["editMarketOrderId"]?.toIntOrNull(),
            editMarketDeliveryOrderId: state
                .uri.queryParameters["editMarketDeliveryOrderId"]
                ?.toIntOrNull(),
            editCheckInventoryRecordId: state
                .uri.queryParameters["editCheckInventoryRecordId"]
                ?.toIntOrNull(),
            editMarketCheckInventoryRecordId: state
                .uri.queryParameters["editMarketCheckInventoryRecordId"]
                ?.toIntOrNull(),
            excludeIds: excludeIds
                    ?.split(",")
                    .map((e) => e.toIntOrNull())
                    .where((element) => element != null)
                    .map((e) => e!)
                    .toList() ??
                [],
            returnItem: returnItem == null ? null : returnItem == "true",
            multiSelect: multiSelect == null ? null : multiSelect == "true",
          );
        },
        parentNavigatorKey: rootGoRouterKey,
        routes: [
          GoRoute(
            path: "new",
            parentNavigatorKey: rootGoRouterKey,
            redirect: _checkAuthorizationRedirect,
            builder: (context, state) {
              return const AddGoodsPage();
            },
          ),
          GoRoute(
            path: ":id",
            parentNavigatorKey: rootGoRouterKey,
            redirect: _checkAuthorizationRedirect,
            builder: (context, state) {
              return GoodsDetailPage(
                id: int.parse(state.pathParameters["id"]!),
              );
            },
            routes: [
              GoRoute(
              path: "edit",
              parentNavigatorKey: rootGoRouterKey,
              redirect: _checkAuthorizationRedirect,
              builder: (context, state) {
                return EditGoodsPage(
                  id: int.parse(state.pathParameters["id"]!),
                );
              },
            ),
            ]
          ),
        ]),
    GoRoute(
      path: UpdatePasswordPage.path,
      redirect: _checkAuthorizationRedirect,
      builder: (context, state) => UpdatePasswordPage(),
      parentNavigatorKey: rootGoRouterKey,
    ),
    GoRoute(
        path: "/checkInventoryRecords",
        redirect: _checkAuthorizationRedirect,
        parentNavigatorKey: rootGoRouterKey,
        builder: (context, state) => const CheckInventoryRecord(),
        routes: [
          GoRoute(
            parentNavigatorKey: rootGoRouterKey,
            redirect: _checkAuthorizationRedirect,
            builder: (context, state) {
              return CheckInventoryRecordDetailPage(
                state.pathParameters["id"]!.toIntOrNull()!,
              );
            },
            path: ':id',
          )
        ]),
    GoRoute(
        path: "/markets/:marketId/checkInventoryRecords",
        redirect: _checkAuthorizationRedirect,
        parentNavigatorKey: rootGoRouterKey,
        builder: (context, state) {
          var marketId = state.pathParameters["marketId"]!.toIntOrNull()!;
          return MarketCheckInventoryRecordPage(marketId: marketId);
        },
        routes: [
          GoRoute(
            parentNavigatorKey: rootGoRouterKey,
            redirect: _checkAuthorizationRedirect,
            builder: (context, state) {
              var id = state.pathParameters["id"]!.toIntOrNull()!;
              return MarketCheckInventoryRecordDetailPage(
                id,
              );
            },
            path: ':id',
          )
        ]),
    GoRoute(
      path: "/goodsScratches",
      redirect: _checkAuthorizationRedirect,
      builder: (context, state) => const GoodsScratchPage(),
      parentNavigatorKey: rootGoRouterKey,
      routes: [
        GoRoute(
          path: ":id",
          parentNavigatorKey: rootGoRouterKey,
          builder: (context, state) {
            return GoodsScratchDetailPage(
                id: int.parse(state.pathParameters["id"]!));
          },
          redirect: _checkAuthorizationRedirect,
        ),
      ],
    ),
  ],
);

class Root extends HookWidget {
  const Root({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var store = Provider.of<EmployeeAuthorizationStore>(context);
    var hasLogin = useObservable(() => store.hasLogin);
    useEffect(() {
      if (hasLogin) {
        if (store.me == null) {
          employeeApi.getMe().then((value) {
            Provider.of<EmployeeAuthorizationStore>(context, listen: false)
                .setMe(value);
          });
        }
        initializeService();
      } else {
        (SharedPreferences.getInstance()).then((value) {
          if (value.containsKey(HttpHeaders.authorizationHeader)) {
            initializeService();
            employeeApi.getMe().then((value) {
              Provider.of<EmployeeAuthorizationStore>(context, listen: false)
                  .setMe(value);
            });
          }
        });
      }
      return null;
    }, [hasLogin]);
    return DynamicColorBuilder(
      builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
        ColorScheme lightScheme;
        ColorScheme darkScheme;

        if (lightDynamic != null && darkDynamic != null) {
          lightScheme = lightDynamic.harmonized();
          lightCustomColors = lightCustomColors.harmonized(lightScheme);

          // Repeat for the dark color scheme.
          darkScheme = darkDynamic.harmonized();
          darkCustomColors = darkCustomColors.harmonized(darkScheme);
        } else {
          // Otherwise, use fallback schemes.
          lightScheme = lightColorScheme;
          darkScheme = darkColorScheme;
        }

        return Provider(
          create: (BuildContext context) {
            return notificationApi;
          },
          child: MaterialApp.router(
            key: materialRouterGlobalKey,
            routerConfig: _router,
            localizationsDelegates: const [
              ...GlobalMaterialLocalizations.delegates,
              GlobalWidgetsLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('zh', 'CH'),
            ],
            title: '智子供应商系统',
            locale: const Locale('zh'),
            theme: ThemeData(
              useMaterial3: true,
              colorScheme: lightScheme,
              extensions: [lightCustomColors],
            ),
            darkTheme: ThemeData(
              useMaterial3: true,
              colorScheme: darkScheme,
              extensions: [darkCustomColors],
            ),
          ),
        );
      },
    );
  }
}
